package com.hs.jhzd.utils;

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import com.hs.jhzd.utils.enums.PictureHeadCode;

public class ImageUtil {

  public static byte[] compressPic(byte[] imageByte, String type) {
    byte[] inByte = null;
    ByteArrayInputStream byteInput = null;
    BufferedImage src = null;
    ByteArrayOutputStream out = null;
    ImageWriter imgWrier;
    ImageWriteParam imgWriteParams;

    // 指定写图片的方式为 jpg
    imgWrier = ImageIO.getImageWritersByFormatName(type).next();
    imgWriteParams = new JPEGImageWriteParam(null);
    // 要使用压缩，必须指定压缩方式为MODE_EXPLICIT
    imgWriteParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    // 这里指定压缩的程度，参数qality是取值0~1范围内，
    imgWriteParams.setCompressionQuality((float) 0.5);
    imgWriteParams.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
    ColorModel colorModel = ColorModel.getRGBdefault();
    // 指定压缩时使用的色彩模式
    imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel,
        colorModel.createCompatibleSampleModel(16, 16)));

    try {
      if (imageByte == null || imageByte.length == 0) {
        return null;
      } else {
        byteInput = new ByteArrayInputStream(imageByte);
        src = ImageIO.read(byteInput);
        out = new ByteArrayOutputStream(imageByte.length);

        imgWrier.reset();
        // 必须先指定 out值，才能调用write方法, ImageOutputStream可以通过任何
        // OutputStream构造
        imgWrier.setOutput(ImageIO.createImageOutputStream(out));
        // 调用write方法，就可以向输入流写图片
        imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams);
        out.flush();
        out.close();
        byteInput.close();
        inByte = out.toByteArray();
      }
    } catch (Exception e) {
      return imageByte;
    }
    return inByte;
  }

  public static String getPicType(byte[] content) {
    String headerString = bytesToHexString(content);
    if (headerString.startsWith(PictureHeadCode.BMP.getValue())) {
      return PictureHeadCode.BMP.getName();
    } else if (headerString.startsWith(PictureHeadCode.PNG.getValue())) {
      return PictureHeadCode.PNG.getName();
    } else if (headerString.startsWith(PictureHeadCode.GIF.getValue())) {
      return PictureHeadCode.GIF.getName();
    } else if (headerString.startsWith(PictureHeadCode.JPEG.getValue())) {
      return PictureHeadCode.JPEG.getName();
    } else {
      return PictureHeadCode.OTHER.getName();
    }
  }

  private static String bytesToHexString(byte[] src) {

    StringBuilder stringBuilder = new StringBuilder();
    if (src == null || src.length <= 0) {
      return null;
    }
    for (int i = 0; i < src.length; i++) {
      int v = src[i] & 0xFF;
      String hv = Integer.toHexString(v);
      if (hv.length() < 2) {
        stringBuilder.append(0);
      }
      stringBuilder.append(hv);
    }
    return stringBuilder.toString();
  }

  // 纵向处理图片
  public static void yPic(List<byte[]> piclist, String outPath) {
    if (piclist == null || piclist.size() <= 0) {
      System.out.println("图片数组为空!");
      return;
    }
    try {
      int height = 0;// 总高度
      int width = 0; // 总宽度
      int _width = 0;
      int _height = 0; // 临时的高度 , 或保存偏移高度
      int __height = 0; // 临时的高度，主要保存每个高度
      int picNum = piclist.size();// 图片的数量
      int[] widthArray = new int[picNum];
      int[] heightArray = new int[picNum]; // 保存每个文件的高度
      BufferedImage buffer = null; // 保存图片流
      List<int[]> imgRgb = new ArrayList<>(); // 保存所有的图片的RGB
      int[] _imgRgb; // 保存一张图片中的RGB数据
      for (int i = 0; i < picNum; i++) {
        ByteArrayInputStream in = new ByteArrayInputStream(piclist.get(i));
        buffer = ImageIO.read(in);
        heightArray[i] = _height = buffer.getHeight();// 图片高度
        widthArray[i] = _width = buffer.getWidth();// 图片宽度
        if (_width > width) {
          width = _width;
        }
        height += _height; // 获取总高度
        _imgRgb = new int[width * _height];// 从图片中读取RGB
        _imgRgb = buffer.getRGB(0, 0, _width, _height, _imgRgb, 0, _width);
        imgRgb.add(_imgRgb);
      }
      _height = 0; // 设置偏移高度为0
      // 生成新图片
      BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      for (int i = 0; i < picNum; i++) {
        __height = heightArray[i];
        if (i != 0) {
          _height += heightArray[i - 1]; // 计算偏移高度
        }
        // 写入流中
        imageResult.setRGB(0, _height, widthArray[i], __height, imgRgb.get(i), 0, widthArray[i]);
      }
      File outFile = new File(outPath);
      if (!outFile.exists()) {
        outFile.mkdirs();
      }
      ImageIO.write(imageResult, "jpg", outFile);// 写图片
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


}
